package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/5 18:33
 */
public class J67 {

    // https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/
    public static int strToInt(String str) {
        if(str == null || str.length() == 0) return 0;
        int res = 0, bndry = Integer.MAX_VALUE/ 10;
        int i = 0, N = str.length();
        boolean sign = true;
        // 跳过前边的空格
        while (str.charAt(i) == ' ') {
            if(++i == str.length())
                return 0;
        }
        // 判断正负数, 并跳过这一位
        if(str.charAt(i) == '-') {
            sign = false;
        }
        if(str.charAt(i) == '-' || str.charAt(i) == '+') {
            i++;
        }
        for (int j = i; j < N; j++) {
            // 根据题目要求: 遇到非数值跳出循环不算了
            if(str.charAt(j) < '0' || str.charAt(j) > '9') {
                break;
            }
            // 如果此时要越界了.直接返回最大值或最小值
            if(res > bndry || res == bndry && str.charAt(j) > '7') {
                return sign? Integer.MAX_VALUE: Integer.MIN_VALUE;
            }
            res = res * 10 + (str.charAt(j) - '0');
        }
        return sign? res: -res;
    }

    // for test
    public static void main(String[] args) {
        String str = "2147483646";
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
        System.out.println(strToInt(str));
    }


}
